#include "can.h"
#include <unistd.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
using namespace std;

canCore::canCore()
{
}

canCore::~canCore()
{
}

void canCore::reading()
{
   /* Create the socket */
   int skt = socket( PF_CAN, SOCK_RAW, CAN_RAW );

   /* Locate the interface you wish to use */
   struct ifreq ifr;
   strcpy(ifr.ifr_name, "can0");
   ioctl(skt, SIOCGIFINDEX, &ifr); /* ifr.ifr_ifindex gets filled
                                     * with that device's index */

   /* Select that CAN interface, and bind the socket to it. */
   struct sockaddr_can addr;
   addr.can_family = AF_CAN;
   addr.can_ifindex = ifr.ifr_ifindex;
   bind( skt, (struct sockaddr*)&addr, sizeof(addr) );

   /* Send a message to the CAN bus */
   struct can_frame frame;
   //frame.can_id = 0x123;
   //strcpy( &frame.data, "foo" );
   //frame.can_dlc = strlen( &frame.data );
   //int bytes_sent = write( skt, &frame, sizeof(frame) );

   /* Read a message back from the CAN bus */
   int bytes_read = read( skt, &frame, sizeof(frame) );
}

char* canCore::fakeReading()
{
   return "Hello";
}

int main()
{
	int skt = socket( PF_CAN, SOCK_RAW, CAN_RAW );
	struct ifreq ifr;
	strcpy(ifr.ifr_name, "can0");
	ioctl(skt, SIOCGIFINDEX, &ifr);
	
	struct sockaddr_can addr;
	addr.can_family = AF_CAN;
	addr.can_ifindex = ifr.ifr_ifindex;
	bind( skt, (struct sockaddr*)&addr, sizeof(addr) );

	struct can_frame frame;
	
	int i = 0;
	while (1)
	{
		int bytes_read = read( skt, &frame, sizeof(frame) );

		//__u32
		//bit 0-28 : CAN identifier (11/29 bit) 
		//bit 29   : error frame flag (0 = data frame, 1 = error frame) 
		//bit 30   : remote transmission request flag (1 = rtr frame) 
		//bit 31   : frame format flag (0 = standard 11 bit, 1 = extended 29 bit)
		canid_t id = frame.can_id;	
		
		//__u8
		//data length code 0->8
		// = frame.can_dic;
		
		//__u8[8]
		// = frame.data;
		
		cout << ++i << " - Frame: " << id << endl;
		usleep(2000000);		
	}
	
	return 1;
}
